package com.wu.common.utils;


import java.io.File;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.wu.common.exception.WexinReqException;
import com.wu.entity.model.*;
import com.wu.entity.weixin.po.WxArticle;
import com.wu.entity.weixin.po.WxMedia;
import com.wu.entity.weixin.po.Wxuser;
import com.wu.entity.weixin.requ.WxArticlesRequest;
import net.sf.json.JSONObject;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JwSendMessageAPI {
    private static Logger logger = LoggerFactory.getLogger(JwSendMessageAPI.class);
    private static String message_preview_url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN";
    private static String upload_media_url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
    private static String upload_article_url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN";
    private static String message_group_url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN";
    private static String message_openid_url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN";
    private static String message_delete_url = "https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token=ACCESS_TOKEN";
    private static String message_get_url = "https://api.weixin.qq.com/cgi-bin/message/mass/get?access_token=ACCESS_TOKEN";
    private static String uploadimg_url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";

    public JwSendMessageAPI() {
    }

    public static String uploadArticleImgs(String content, String accesstoken, String baseImageUrl, String domain) {
        try {
            String[] urls = ReadImgUrls.getImgs(content);
            String[] var5 = urls;
            int var6 = urls.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                String imgurl = var5[var7];
                if (imgurl.indexOf("mmbiz.qpic.cn") == -1) {
                    String tempimgurl = imgurl.replace(domain, "");
                    tempimgurl = baseImageUrl + tempimgurl;
                    String newUrl = uploadImg(accesstoken, tempimgurl);
                    content = content.replace(imgurl, newUrl);
                }
            }
        } catch (Exception var11) {
            System.err.println(var11.toString());
        }

        return content;
    }

    public static String uploadImg(String accesstoken, String filePath) {
        try {
            if (accesstoken != null) {
                String requestUrl = uploadimg_url.replace("ACCESS_TOKEN", accesstoken);
                HttpPostUtil u = new HttpPostUtil(requestUrl);
                u.addFileParameter("img", new File(filePath));
                JSONObject result = JSONObject.fromObject(new String(u.send()));
                if (result != null) {
                    if (result.containsKey("url")) {
                        return result.getString("url");
                    }

                    System.err.println(result.toString());
                }
            }
        } catch (Exception var5) {
            System.err.println(var5.toString());
        }

        return "";
    }

    public static JSONObject uploadImgReturnObj(String accesstoken, String filePath) {
        JSONObject result = new JSONObject();

        try {
            if (accesstoken != null) {
                String requestUrl = uploadimg_url.replace("ACCESS_TOKEN", accesstoken);
                HttpPostUtil u = new HttpPostUtil(requestUrl);
                u.addFileParameter("img", new File(filePath));
                result = JSONObject.fromObject(new String(u.send()));
                if (result != null && !result.containsKey("url")) {
                    System.err.println(result.toString());
                }
            }
        } catch (Exception var5) {
            result.put("errmsg", var5.toString());
            result.put("errcode", "");
            System.err.println(var5.toString());
        }

        return result;
    }

    public static void messagePrivate(String accesstoken, String touser, List<WxArticle> wxArticles) throws WexinReqException {
        if (accesstoken != null) {
            String requestUrl = message_preview_url.replace("ACCESS_TOKEN", accesstoken);

            try {
                String mediaId = getMediaId(accesstoken, wxArticles);
                JSONObject obj = new JSONObject();
                JSONObject mpnews = new JSONObject();
                obj.put("touser", touser);
                obj.put("msgtype", "mpnews");
                mpnews.put("media_id", mediaId);
                obj.put("mpnews", mpnews);
                WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
            } catch (Exception var8) {
                throw new WexinReqException(var8);
            }
        } else {
            throw new WexinReqException("accesstoken 为空，请检查！");
        }
    }

    public static String messagePrivate(String accesstoken, String touser, String content) throws WexinReqException {
        String ret = "";
        if (accesstoken != null) {
            String requestUrl = message_preview_url.replace("ACCESS_TOKEN", accesstoken);

            try {
                JSONObject obj = new JSONObject();
                JSONObject text = new JSONObject();
                obj.put("touser", touser);
                obj.put("msgtype", "text");
                text.put("content", content);
                obj.put("text", text);
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                ret = result.toString();
                return ret;
            } catch (Exception var8) {
                throw new WexinReqException(var8);
            }
        } else {
            throw new WexinReqException("accesstoken 为空，请检查！");
        }
    }

    public static void messagePrivate(String accesstoken, String touser, WxMedia wxMedia) throws WexinReqException {
        if (accesstoken != null) {
            String requestUrl = message_preview_url.replace("ACCESS_TOKEN", accesstoken);

            try {
                String mediaId = getMediaId(accesstoken, wxMedia);
                JSONObject obj = new JSONObject();
                JSONObject type = new JSONObject();
                obj.put("touser", touser);
                obj.put("msgtype", wxMedia.getType());
                type.put("media_id", mediaId);
                obj.put(wxMedia.getType(), type);
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                if (result.getInt("errcode") != 0) {
                    logger.error("多媒体消息预览失败！errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg"));
                    throw new Exception("多媒体消息预览失败！errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg"));
                }
            } catch (Exception var8) {
                throw new WexinReqException(var8);
            }
        } else {
            throw new WexinReqException("accesstoken 为空，请检查！");
        }
    }

    public static SendMessageResponse sendMessageToGroupOrAllWithArticles(String accesstoken, boolean is_to_all, Group group, List<WxArticle> wxArticles) throws WexinReqException {
        SendMessageResponse response = null;
        if (accesstoken != null) {
            String requestUrl = message_group_url.replace("ACCESS_TOKEN", accesstoken);

            try {
                String mediaId = getMediaId(accesstoken, wxArticles);
                JSONObject obj = new JSONObject();
                JSONObject filter = new JSONObject();
                JSONObject mpnews = new JSONObject();
                filter.put("is_to_all", is_to_all);
                if (!is_to_all) {
                    filter.put("group_id", group.getId());
                }

                obj.put("filter", filter);
                mpnews.put("media_id", mediaId);
                obj.put("mpnews", mpnews);
                obj.put("msgtype", "mpnews");
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                response = (SendMessageResponse)JSONObject.toBean(result, SendMessageResponse.class);
                return response;
            } catch (Exception var11) {
                throw new WexinReqException(var11);
            }
        } else {
            throw new WexinReqException("accesstoken 为空，请检查！");
        }
    }

    public static SendMessageResponse sendMessageToGroupOrAllWithText(String accesstoken, boolean is_to_all, Group group, String content) throws WexinReqException {
        SendMessageResponse response = null;
        if (accesstoken != null) {
            String requestUrl = message_group_url.replace("ACCESS_TOKEN", accesstoken);

            try {
                JSONObject obj = new JSONObject();
                JSONObject filter = new JSONObject();
                JSONObject text = new JSONObject();
                filter.put("is_to_all", is_to_all);
                if (!is_to_all) {
                    filter.put("group_id", group.getId());
                }

                obj.put("filter", filter);
                text.put("content", content);
                obj.put("text", text);
                obj.put("msgtype", "text");
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                response = (SendMessageResponse)JSONObject.toBean(result, SendMessageResponse.class);
                return response;
            } catch (Exception var10) {
                throw new WexinReqException(var10);
            }
        } else {
            throw new WexinReqException("accesstoken 为空，请检查！");
        }
    }

    public static SendMessageResponse sendMessageToGroupOrAllWithMedia(String accesstoken, boolean is_to_all, Group group, WxMedia wxMedia) throws WexinReqException {
        SendMessageResponse response = null;
        if (accesstoken != null) {
            String requestUrl = message_group_url.replace("ACCESS_TOKEN", accesstoken);

            try {
                String mediaId = getMediaId(accesstoken, wxMedia);
                JSONObject obj = new JSONObject();
                JSONObject filter = new JSONObject();
                JSONObject media = new JSONObject();
                filter.put("is_to_all", is_to_all);
                if (!is_to_all) {
                    filter.put("group_id", group.getId());
                }

                obj.put("filter", filter);
                media.put("media_id", mediaId);
                obj.put(wxMedia.getType(), media);
                obj.put("msgtype", wxMedia.getType());
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                response = (SendMessageResponse)JSONObject.toBean(result, SendMessageResponse.class);
                return response;
            } catch (Exception var11) {
                throw new WexinReqException(var11);
            }
        } else {
            throw new WexinReqException("accesstoken 为空，请检查！");
        }
    }

    public static SendMessageResponse sendMessageToOpenidsWithArticles(String accesstoken, Wxuser[] wxusers, List<WxArticle> wxArticles) throws WexinReqException {
        SendMessageResponse response = null;
        if (accesstoken == null) {
            throw new WexinReqException("accesstoken 为空，请检查！");
        } else {
            String requestUrl = message_openid_url.replace("ACCESS_TOKEN", accesstoken);
            List<String> openids = new ArrayList();
            Wxuser[] var6 = wxusers;
            int var7 = wxusers.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                Wxuser wxuser = var6[var8];
                openids.add(wxuser.getOpenid());
            }

            try {
                String mediaId = getMediaId(accesstoken, wxArticles);
                JSONObject obj = new JSONObject();
                JSONObject mpnews = new JSONObject();
                obj.put("touser", openids);
                mpnews.put("media_id", mediaId);
                obj.put("mpnews", mpnews);
                obj.put("msgtype", "mpnews");
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                response = (SendMessageResponse)JSONObject.toBean(result, SendMessageResponse.class);
                return response;
            } catch (Exception var10) {
                throw new WexinReqException(var10);
            }
        }
    }

    public static SendMessageResponse sendMessageToOpenidsWithText(String accesstoken, Wxuser[] wxusers, String content) throws WexinReqException {
        SendMessageResponse response = null;
        if (accesstoken == null) {
            throw new WexinReqException("accesstoken 为空，请检查！");
        } else {
            String requestUrl = message_openid_url.replace("ACCESS_TOKEN", accesstoken);
            List<String> openids = new ArrayList();
            Wxuser[] var6 = wxusers;
            int var7 = wxusers.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                Wxuser wxuser = var6[var8];
                openids.add(wxuser.getOpenid());
            }

            try {
                JSONObject obj = new JSONObject();
                JSONObject text = new JSONObject();
                obj.put("touser", openids);
                text.put("content", content);
                obj.put("text", text);
                obj.put("msgtype", "text");
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                response = (SendMessageResponse)JSONObject.toBean(result, SendMessageResponse.class);
                return response;
            } catch (Exception var10) {
                throw new WexinReqException(var10);
            }
        }
    }

    public static SendMessageResponse sendMessageToOpenidsWithMedia(String accesstoken, Wxuser[] wxusers, WxMedia wxMedia) throws WexinReqException {
        SendMessageResponse response = null;
        if (accesstoken == null) {
            throw new WexinReqException("accesstoken 为空，请检查！");
        } else {
            String requestUrl = message_openid_url.replace("ACCESS_TOKEN", accesstoken);
            List<String> openids = new ArrayList();
            Wxuser[] var6 = wxusers;
            int var7 = wxusers.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                Wxuser wxuser = var6[var8];
                openids.add(wxuser.getOpenid());
            }

            try {
                String mediaId = getMediaId(accesstoken, wxMedia);
                JSONObject obj = new JSONObject();
                JSONObject media = new JSONObject();
                obj.put("touser", openids);
                media.put("media_id", mediaId);
                obj.put(wxMedia.getType(), media);
                obj.put("msgtype", wxMedia.getType());
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                response = (SendMessageResponse)JSONObject.toBean(result, SendMessageResponse.class);
                return response;
            } catch (Exception var10) {
                throw new WexinReqException(var10);
            }
        }
    }

    public static String deleteSendMessage(String accesstoken, String msg_id) throws WexinReqException {
        String response = null;
        if (accesstoken != null) {
            String requestUrl = message_delete_url.replace("ACCESS_TOKEN", accesstoken);

            try {
                JSONObject obj = new JSONObject();
                obj.put("msg_id", msg_id);
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                response = result.toString();
                return response;
            } catch (Exception var6) {
                throw new WexinReqException(var6);
            }
        } else {
            throw new WexinReqException("accesstoken 为空，请检查！");
        }
    }

    public static boolean getSendMessageStatus(String accesstoken, String msg_id) throws WexinReqException {
        boolean response = false;
        if (accesstoken != null) {
            String requestUrl = message_get_url.replace("ACCESS_TOKEN", accesstoken);

            try {
                JSONObject obj = new JSONObject();
                obj.put("msg_id", msg_id);
                JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
                if (result.containsKey("msg_status") && "SEND_SUCCESS".equalsIgnoreCase(result.getString("msg_status"))) {
                    response = true;
                }

                return response;
            } catch (Exception var6) {
                throw new WexinReqException(var6);
            }
        } else {
            throw new WexinReqException("accesstoken 为空，请检查！");
        }
    }

    public static SendMessageReport getReportBySendMessageReturnString(String xmlString) throws WexinReqException {
        SendMessageReport report = new SendMessageReport();
        SAXBuilder build = new SAXBuilder();
        Document doc = null;

        try {
            doc = build.build(new StringReader(xmlString));
        } catch (Exception var13) {
            var13.printStackTrace();
            throw new WexinReqException(var13);
        }

        Element root = doc.getRootElement();
        Iterator itr = root.getChildren().iterator();
        Class clazz = SendMessageReport.class;

        while(itr.hasNext()) {
            Element oneLevelDeep = (Element)itr.next();

            try {
                Field filed = clazz.getDeclaredField(oneLevelDeep.getName());
                filed.setAccessible(true);
                filed.set(report, oneLevelDeep.getText());
                filed.setAccessible(false);
            } catch (NoSuchFieldException var9) {
            } catch (SecurityException var10) {
            } catch (IllegalArgumentException var11) {
            } catch (IllegalAccessException var12) {
            }
        }

        return report;
    }

    public static String getMediaId(String accesstoken, WxMedia wxMedia) throws WexinReqException {
        WxMediaResponse response = uploadMediaFile(accesstoken, wxMedia.getFilePath(), wxMedia.getFileName(), wxMedia.getType());
        if (response == null) {
            throw new WexinReqException("获取多媒体资源的mediaId失败");
        } else {
            return response.getMedia_id();
        }
    }

    public static String getMediaId(String accesstoken, List<WxArticle> wxArticles) throws WexinReqException {
        WxArticlesResponse response = uploadArticles(accesstoken, wxArticles);
        if (response == null) {
            throw new WexinReqException("获取图文的mediaId失败");
        } else {
            return response.getMedia_id();
        }
    }

    public static WxArticlesResponse uploadArticles(String accesstoken, List<WxArticle> wxArticles) throws WexinReqException {
        WxArticlesResponse wxArticlesResponse = null;
        if (wxArticles.size() == 0) {
            logger.error("没有上传的图文消息");
        } else if (wxArticles.size() > 10) {
            logger.error("图文消息最多为10个图文");
        } else if (accesstoken != null) {
            String requestUrl = upload_article_url.replace("ACCESS_TOKEN", accesstoken);
            Iterator var4 = wxArticles.iterator();

            while(var4.hasNext()) {
                WxArticle article = (WxArticle)var4.next();
                if (article.getFileName() != null && article.getFileName().length() > 0) {
                    try {
                        String mediaId = getFileMediaId(accesstoken, article);
                        article.setThumb_media_id(mediaId);
                    } catch (Exception var7) {
                        throw new WexinReqException(var7);
                    }
                }
            }

            WxArticlesRequest wxArticlesRequest = new WxArticlesRequest();
            wxArticlesRequest.setArticles(wxArticles);
            JSONObject obj = JSONObject.fromObject(wxArticlesRequest);
            JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
            if (result.has("errcode")) {
                logger.error("上传图文消息失败！errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg"));
                throw new WexinReqException("上传图文消息失败！errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg"));
            }

            wxArticlesResponse = new WxArticlesResponse();
            wxArticlesResponse.setMedia_id(result.getString("media_id"));
            wxArticlesResponse.setType(result.getString("type"));
            wxArticlesResponse.setCreated_at(new Date(result.getLong("created_at") * 1000L));
        }

        return wxArticlesResponse;
    }

    public static String getFileMediaId(String accesstoken, WxArticle article) throws WexinReqException {
        WxMediaResponse response = uploadMediaFile(accesstoken, article.getFilePath(), article.getFileName(), "image");
        if (response != null) {
            return response.getMedia_id();
        } else {
            throw new WexinReqException("获取文件的media_id失败");
        }
    }

    public static WxMediaResponse uploadMediaFile(String accesstoken, String filePath, String fileName, String type) throws WexinReqException {
        WxMediaResponse mediaResource = null;
        if (accesstoken != null) {
            String requestUrl = upload_media_url.replace("ACCESS_TOKEN", accesstoken).replace("TYPE", type);
            File file = new File(filePath + fileName);
            String contentType = WeiXinReqUtil.getFileContentType(fileName.substring(fileName.lastIndexOf(".") + 1));
            JSONObject result = WxstoreUtils.uploadMediaFile(requestUrl, file, contentType);
            if (result.containsKey("errcode")) {
                logger.error("上传媒体资源失败！errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg"));
            } else {
                mediaResource = new WxMediaResponse();
                mediaResource.setMedia_id(result.getString("media_id"));
                mediaResource.setType(result.getString("type"));
                mediaResource.setCreated_at(new Date(result.getLong("created_at") * 1000L));
            }
        }

        return mediaResource;
    }

    public static void main(String[] args) throws WexinReqException {
    }
}

